package tk.xboot.boot.conf;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * PG data source conf.
 */

@Configuration
@MapperScan(basePackages = "tk.xboot.boot.dao.mapper.pg", sqlSessionFactoryRef = "pgSessionFactory")
public class PGDataSourceConf {


    @Bean("pg")
    @ConfigurationProperties("app.ds2")
    public DataSource ds2() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }


    @Bean(name = "pgJdbcTemplate")
    public JdbcTemplate pgJdbcTemplate() {
        JdbcTemplate template = new JdbcTemplate();
        template.setDataSource(ds2());
        return template;
    }


    /**
     * PG的transactionManager.
     * <p>
     * 在使用PG 的事务时，需要指定此TransactionManager
     * e.g.
     *
     * @return
     * @Transactional(transactionManager="pgTransactionManager")
     */
    @Bean("pgTxMgr")
    public PlatformTransactionManager pgTransactionManager() {
        return new DataSourceTransactionManager(ds2());
    }


    @Bean
    public SqlSessionFactory pgSessionFactory() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(ds2());
        return bean.getObject();
    }
}
